//
//  CreateOrder.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import UIKit

class CreateOrder: ZMViewController {
    //MARK: --------------------属性--------------------
    var orderNo = ""
    
    var orderInfo = ZMUtil.fastNilBehavior(type: VIPMallModels.PreOrderDetial.self)
    //MARK: --------------------UI控件--------------------
    let scrollView = UIScrollView()
    
    let bottomView = UIView()
    
    let confirmButton = ZMUtil.defalutBottomButton(title: "提交订单", font: UIFont.systemFont(ofSize: 14), height: 38)
    
    let scrollContent = ZMUtil.stackView(axis: .vertical, spacing: 16)
    
    let addressView = ZMOrderAddressView().then({$0.layer.cornerRadius=12;$0.layer.masksToBounds=true})
    
    let goodsView = CreateOrderGoodsView().then({$0.layer.cornerRadius=12;$0.layer.masksToBounds=true})
    
    let loading = XMLoadingView()
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loadInfo()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "确认订单"
        view.addSubview(scrollView)
        scrollView.backgroundColor = "#F5F5F5".zm.hex()
        view.addSubview(bottomView)
        bottomView.addSubview(confirmButton)
        
        scrollContent.addArrangedSubview(addressView)
        
        scrollView.addSubview(scrollContent)
        
        addressView.address = nil
        
        scrollContent.addArrangedSubview(goodsView)
        
        loading.showInView(fatherView: view)
    }
    
    
    func addConstraints() {
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(56)
        }
        
        confirmButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.height.equalTo(38)
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        scrollContent.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.centerX.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        addressView.clickBlock = {[weak self] in
            guard let self = self else {return}
            let vc = ZMAddressListVC()
            vc.chooseAddressBlock = { address in
                guard var temp = self.orderInfo.value else {return}
                temp.orderInfoVo.addressId = address.id
                temp.orderInfoVo.city = address.city
                temp.orderInfoVo.district = address.district
                temp.orderInfoVo.province = address.province
                temp.orderInfoVo.phone = address.phone
                temp.orderInfoVo.realName = address.realName
                temp.orderInfoVo.detail = address.detail
                self.orderInfo.accept(temp)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        confirmButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.createOrder()
        }).disposed(by: disposeBag)
        
        // 绑定详情
        orderInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            let orderInfo = resp.orderInfoVo
            if resp.orderInfoVo.addressId > 0 {
                // 有地址
                var addModel = AddressModel()
                addModel.id = orderInfo.addressId
                addModel.city = orderInfo.city
                addModel.district = orderInfo.district
                addModel.province = orderInfo.province
                addModel.phone = orderInfo.phone
                addModel.realName = orderInfo.realName
                addModel.detail = orderInfo.detail
                addressView.address = addModel
            } else {
                addressView.address = nil
            }
            
            // 商品信息
            self.goodsView.title.text = "共\(orderInfo.orderProNum)件商品"
            self.goodsView.name.text = orderInfo.orderInfoDetailVo.productName
            self.goodsView.activityNum.setTitle("+\(orderInfo.orderInfoDetailVo.giveActivity.zm.toString(keep: 4))活跃度", for: .normal)
            self.goodsView.activityNum.sizeToFit()
            if orderInfo.orderInfoDetailVo.type == 4 {
                // 积分商品
                self.goodsView.unit.isHidden = true
                self.goodsView.price.text = orderInfo.orderInfoDetailVo.integralPrice.zm.toString(keep: 2) + "积分"
            } else {
                self.goodsView.price.text = orderInfo.proTotalFee.zm.toString(keep: 2)
            }
            self.goodsView.img.zm.setImage(urlStr: orderInfo.orderInfoDetailVo.image)
            self.goodsView.layoutSubviews()
            self.goodsView.activityNum.isHidden = !((orderInfo.orderInfoDetailVo.type == 0 || orderInfo.orderInfoDetailVo.type == 4) && orderInfo.orderInfoDetailVo.giveActivity > 0)
            
        }).disposed(by: disposeBag)
    }
    
    func loadInfo() {
        VIPMallAPI.getPreOrderInfo(orderNo).rxRequest(type: VIPMallModels.PreOrderDetial.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.orderInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func createOrder() {
        guard let orderInfo = orderInfo.value else {
            ZMToast.showToast(title: "未获取到预下单信息")
            return}
        if orderInfo.orderInfoVo.addressId == 0 {
            ZMToast.showToast(title: "请选择地址")
            return
        }
        
//        orderInfoDetailVo.type
        var payStr = "weixin"

        if orderInfo.orderInfoVo.orderInfoDetailVo.type == 4 {
            payStr = VIPMallService.shared.getPayStr(type: .integral)
        }
        let pa = [
            "addressId" : orderInfo.orderInfoVo.addressId,
            "mark" : "",
            "payType" : payStr,
            "preOrderNo" : orderNo
        ] as [String : Any]
        ZMToast.showActivity()
        VIPMallAPI.createOrder(pa).rxRequest(type: [String : String].self).subscribe(onNext:{ [unowned self] resp in
            let orderNo = JSON(resp)["orderNo"].stringValue
            ZMToast.hiddenActivity()
            if let vc = router.viewController(for: "xm://main/VIPMall/order_detail", context: ["orderNo" : orderNo]) {
                self.replace(vc)
            }
        }).disposed(by: disposeBag)
    }

    //MARK: --------------------delegate--------------------
}
